package com.tan.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tan.common.domain.user.SysRoleMenu;
import com.tan.common.domain.user.SysRoleMenu;
import com.tan.common.dto.user.RoleMenuDTO;
import com.tan.common.mapper.user.SysRoleMenuMapper;
import com.tan.user.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色和菜单关联表 服务实现类
 * </p>
 *
 * @author Tan
 * @since 2025-01-27
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {


    @Override
    public List<SysRoleMenu> byMenu(Long menuId) {
        return this.baseMapper.selectList(Wrappers.lambdaQuery(SysRoleMenu.class).eq(SysRoleMenu::getMenuId, menuId));
    }

    @Override
    public List<SysRoleMenu> byRole(Long roleId) {
        return this.baseMapper.selectList(Wrappers.lambdaQuery(SysRoleMenu.class).eq(SysRoleMenu::getRoleId, roleId));
    }

    @Override
    public List<SysRoleMenu> byRole(List<Long> ids) {
        if (ids.isEmpty()) {
            return Collections.emptyList();
        }
        return this.baseMapper.selectList(Wrappers.lambdaQuery(SysRoleMenu.class).in(SysRoleMenu::getRoleId, ids));
    }

    @Override
    public List<Long> rolesByMenu(Long menuId) {
        return this.byMenu(menuId).stream().map(SysRoleMenu::getRoleId).collect(Collectors.toList());
    }

    @Override
    public List<Long> menusByRole(Long roleId) {
        return this.byRole(roleId).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
    }

    @Override
    public Set<Long> rolesByMenu(List<Long> ids) {
        return this.byRole(ids).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet());
    }

    @Override
    public void delByRole(Long roleId) {
        this.baseMapper.deleteById(roleId);
    }

    @Override
    public void insertBatch(RoleMenuDTO roleMenuDTO) {
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        roleMenuDTO.getMenuId().forEach(e -> {
            sysRoleMenus.add(SysRoleMenu.builder().menuId(e).roleId(roleMenuDTO.getRoleId()).build());
        });
        this.baseMapper.insert(sysRoleMenus);
    }
}
